package com.miage.kangourou.client.calendar;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

public final class Util {
	/**
	 * Get the week number
	 */
	private static final int ISO_THURSDAY = 4;
	private static final int MAX_DAY_OF_WEEK = 6;
	private static final int DAYS_IN_WEEK = 7;
	private static final long MILLIS_DAY = 86400000;

	public static Date addDays(Date sourceDate, long days) {
		return new Date(sourceDate.getTime() + (days * MILLIS_DAY));
	}

	public static int dayDiff(Date firstDate, Date secondDate) {
		return (int) ((firstDate.getTime() - secondDate.getTime()) / MILLIS_DAY);
	}

	/**
	 * Get the week number
	 * 
	 * @param date
	 *            : Input date
	 * @return : Number of the week (1 - 52)
	 */
	public static int getWeek(Date date) {
		// http://en.wikipedia.org/wiki/Talk:ISO_week_date#Algorithms

		// ISO week day (Mon=1 to Sun=7)
		final int dayOfWeek = 1 + (date.getDay() + MAX_DAY_OF_WEEK)
				% DAYS_IN_WEEK;
		final Date nearestThu = addDays(date, ISO_THURSDAY - dayOfWeek);
		final int year = nearestThu.getYear();
		final Date jan1 = new Date(year, 0, 1);
		return 1 + dayDiff(nearestThu, jan1) / DAYS_IN_WEEK;
	}

	public static String toMd5(String s) {
		byte[] uniqueKey = s.getBytes();
		byte[] hash = null;

		try {
			hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
		} catch (NoSuchAlgorithmException e) {
			throw new Error("No MD5 support in this VM.");
		}

		StringBuilder hashString = new StringBuilder();
		for (int i = 0; i < hash.length; i++) {
			String hex = Integer.toHexString(hash[i]);
			if (hex.length() == 1) {
				hashString.append('0');
				hashString.append(hex.charAt(hex.length() - 1));
			} else {
				hashString.append(hex.substring(hex.length() - 2));
			}
		}
		return hashString.toString();

	}
}
